package com.work.chat.custom.server.config;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.auth0.jwt.JWT;
import com.work.chat.common.eums.BizCodeEnum;
import com.work.chat.custom.server.config.exception.BizException;
import com.work.chat.custom.server.config.model.UserInfo;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class GlobalInterceptor implements HandlerInterceptor {

    @Value("${chat.jwt.secret-key}")
    private String secretKey;
    
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");
        if (!StringUtils.hasText(token) )
        {
            throw  new BizException(BizCodeEnum.NOT_TOKEN_ERROR);
        }
        if (!token.startsWith("Bearer "))
        {
            throw new BizException(BizCodeEnum.JWT_TOKEN_ERROR);
        }
        try {
        Claims body = Jwts.parser().setSigningKey(secretKey).parseClaimsJws(token.replace("Bearer ","")).getBody();
        Object userInfo = body.get("userInfo");
         if (ObjectUtils.isEmpty(userInfo))
         {
             throw new BizException(BizCodeEnum.TOKEN_ERROR);
         }
            JSONObject jsonObject = JSON.parseObject(userInfo.toString());
            if (ObjectUtils.isEmpty(jsonObject))
            {
                throw new BizException(BizCodeEnum.JWT_TOKEN_ERROR);
            }
            //UserInfo userInfos = JSON.parseObject(userInfo.toString(),UserInfo.class);
            LocalUserInfoAccessContext.set(
                    UserInfo.builder()
                    .userId(Long.valueOf(jsonObject.getInteger("userId")))
                    .build());
             return true;
         }
         catch (Exception e)
         {
             throw new BizException(BizCodeEnum.JWT_TOKEN_ERROR);
         }

    }


    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
     LocalUserInfoAccessContext.clear();
    }
}
